import { queryParkinglotNames } from '@/pages/Parking/Spot/service';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/types.d';
import {
  ModalForm,
  ProFormDateTimeRangePicker,
  ProFormRadio,
  ProFormSelect,
} from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import type * as moment from 'moment';
import { useState } from 'react';
import { useModel } from 'umi';
import { exportParkingOrders } from '../service';

const ExportOrder = () => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  const [form] = Form.useForm();
  const [exportType, setExportType] = useState<string>('parkinglot');
  const [ownerName, setOwnerName] = useState<string>('');
  const [parklotName, setParklotName] = useState<string>('');
  return (
    <ModalForm
      title="订单导出"
      submitter={false}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 12 }}
      width={800}
      form={form}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      trigger={<Button type="primary">订单数据导出</Button>}
    >
      <ProFormRadio.Group
        radioType="button"
        label="导出类型"
        initialValue={exportType}
        fieldProps={{
          value: exportType,
          onChange: (e) => {
            setExportType(e.target.value);
            if (e.target.value == 'enterprise') {
              if (form?.resetFields) {
                form.resetFields(['parkingLotId']);
              }
            } else {
              // form.setFieldValue('ownerId', undefined);
              if (form?.resetFields) {
                form.resetFields(['ownerId']);
              }
            }
          },
        }}
        options={
          userRole === Role.ADMIN
            ? [
                { label: '按照用户', value: 'enterprise' },
                { label: '按照路段', value: 'parkinglot' },
              ]
            : [{ label: '按照路段', value: 'parkinglot' }]
        }
      />
      {exportType === 'enterprise' && (
        <ProFormSelect
          label="选择用户"
          name="ownerId"
          required={exportType === 'enterprise'}
          debounceTime={300}
          placeholder="请选择所属用户"
          fieldProps={{
            onChange: (_, option: any) => {
              if (option) setOwnerName(option.label);
            },
          }}
          showSearch
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
      {exportType === 'parkinglot' && (
        <ProFormSelect
          label="选择路段"
          name="parkingLotId"
          required={exportType === 'parkinglot'}
          debounceTime={300}
          placeholder="请选择路段"
          fieldProps={{
            onChange: (_, option: any) => {
              if (option) setParklotName(option.label);
            },
          }}
          showSearch
          request={(val) => queryParkinglotNames(val.keyWords)}
        />
      )}
      <ProFormDateTimeRangePicker name="inTime" label="驶入时间区间" />
      <ProFormDateTimeRangePicker name="outTime" label="驶出时间区间" />

      <div
        style={{
          margin: '0 auto',
          width: '60%',
          padding: '15px 0',
          verticalAlign: 'middle',
          textAlign: 'center',
          background: '#f4f6fa',
        }}
      >
        {userRole === Role.ADMIN && (
          <p style={{ marginTop: 0 }}>按照用户：选择指定用户名下订单数据导出</p>
        )}
        <p>按照路段：选择指定路段下的订单数据导出</p>
        <p style={{ color: 'red' }}>时间区间：驶入/驶出时间区间不可全部为空</p>
        <p style={{ fontSize: '12px', marginBottom: 0, color: '#999' }}>
          * 所导出的订单中将不会包含已经作废的订单
        </p>
      </div>
      <Button
        type="primary"
        style={{
          margin: '20px auto',
          display: 'block',
          textAlign: 'center',
        }}
        onClick={async () => {
          message.info({ key: 'export_order', content: '正在导出文件，请稍后……' });
          const params = form.getFieldsValue();
          const { parkingLotId, ownerId, inTime, outTime } = params;

          if (exportType === 'parkinglot' && !parkingLotId) {
            message.error({ content: '请选择路段', key: 'export_order' });
            return false;
          }
          if (exportType === 'enterprise' && !ownerId) {
            message.error({ content: '请选择所属用户', key: 'export_order' });
            return false;
          }
          if (!inTime && !outTime) {
            message.error({ content: '请至少选择一种时间约束', key: 'export_order' });
            return false;
          }
          const exportParams: Record<string, any> = {};
          if (exportType === 'parkinglot' && parkingLotId) {
            exportParams.parkingLotId = parkingLotId;
          }
          if (exportType === 'enterprise' && ownerId) {
            exportParams.ownerId = ownerId;
          }
          if (inTime && inTime.length == 2) {
            const [start, end] = inTime;
            const diff = start?.valueOf() - end?.valueOf();
            if (Math.abs(diff) > 1000 * 60 * 60 * 24 * 7) {
              message.error({
                content: '当前所选择的驶入时间间隔大于7天，请重新选择',
                key: 'export_order',
              });
              return false;
            }
            exportParams.inTime = inTime.map((item: moment.Moment) => item.valueOf());
          }
          if (outTime && outTime.length == 2) {
            const [start, end] = outTime;
            const diff = start?.valueOf() - end?.valueOf();
            if (Math.abs(diff) > 1000 * 60 * 60 * 24 * 7) {
              message.error({
                content: '当前所选择的驶出时间间隔大于7天，请重新选择',
                key: 'export_order',
              });
              return false;
            }
            exportParams.outTime = outTime.map((item: moment.Moment) => item.valueOf());
          }
          const res = await exportParkingOrders(exportParams);
          if (!res) {
            message.error({ content: '导出失败', key: 'export_order' });
            return false;
          }
          if (res?.code) {
            message.error({ content: res?.message || '导出失败', key: 'export_order' });
            return false;
          }
          let filename = `订单列表_`;
          if (ownerId) filename += `${ownerName}_`;
          if (parkingLotId) filename += `${parklotName}_`;
          filename += `${new Date().toLocaleString()}.xlsx`;
          const downloadElement = document.createElement('a');
          const herf = window.URL.createObjectURL(
            new Blob([res], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            }),
          );
          downloadElement.href = herf;
          downloadElement.download = filename;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(herf); // 释放blob对象
          return true;
        }}
      >
        下载Excel格式文件
      </Button>
    </ModalForm>
  );
};

export default ExportOrder;
